package com.zjw.zy.componse.demo.view

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.GestureDetector
import android.view.GestureDetector.SimpleOnGestureListener
import android.view.MotionEvent
import android.view.SurfaceHolder
import android.view.SurfaceView
import com.zjw.zy.componse.demo.R
import com.zjw.zy.componse.demo.viewmodel.MineGameViewModel
import com.zjw.zy.componse.demo.viewmodel.MineGameViewModel.Companion.ITEM_STATUS_BANG
import com.zjw.zy.componse.demo.viewmodel.MineGameViewModel.Companion.ITEM_STATUS_BLACK
import com.zjw.zy.componse.demo.viewmodel.MineGameViewModel.Companion.ITEM_STATUS_FLAG
import com.zjw.zy.componse.demo.viewmodel.MineGameViewModel.Companion.ITEM_STATUS_UN_CLICK
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

/**
 * @author ：zhong.jw
 * @date ：Created in 2023/3/6 11:01
 */
class MineGameSurfaceView : SurfaceView, SurfaceHolder.Callback {

    private var heightCount: Int = 0
    private var widthCount: Int = 0

    /*渲染线程*/
    private lateinit var render: ExecutorService

    private val mGestureDetector = GestureDetector(context, object : SimpleOnGestureListener() {
        override fun onSingleTapUp(e: MotionEvent): Boolean {
            vm.performClickItem((e.x / itemSize).toInt(), (e.y / itemSize).toInt(), false)
            drawGame()
            return true
        }

        override fun onLongPress(e: MotionEvent) {
            vm.performClickItem((e.x / itemSize).toInt(), (e.y / itemSize).toInt(), true)
            drawGame()
        }
    })

    private val itemStateBgInit = BitmapFactory.decodeResource(resources, R.drawable.bg_src_game_item_status_0,BitmapFactory.Options().apply {
        outHeight = itemSize.toInt()
        outWidth = itemSize.toInt()
    })
    private val itemStateBgClicked = BitmapFactory.decodeResource(resources, R.drawable.bg_src_game_item_status_3)
    private val itemStateBgBang = BitmapFactory.decodeResource(resources, R.drawable.bg_src_game_item_status_1)
    private val itemStateBgFlag = BitmapFactory.decodeResource(resources, R.drawable.bg_src_game_item_status_2)

    private var height = 0
    private var width = 0
    private var itemSize = 50f

    private val p = Paint().apply {
        color = Color.GRAY
        textSize = 22f
    }

    private val vm = MineGameViewModel()

    constructor(context: Context) : super(context) {
        onInitSelf(context)
    }

    private fun onInitSelf(context: Context) {
        this.holder.addCallback(this)
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        render.shutdown()
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        render = Executors.newSingleThreadExecutor()
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {}
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context, attrs, defStyleAttr
    ) {
    }


    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent): Boolean {
        mGestureDetector.onTouchEvent(event)
        return true
    }

    override fun surfaceCreated(holder: SurfaceHolder) {

    }

    override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
        this.height = height
        this.width = width
        widthCount = (width / itemSize).toInt()
        heightCount = (height / itemSize).toInt()
        vm.initGame(heightCount, widthCount)
        drawGame()
    }

    private fun drawGame() {
        render.submit {
            val canvas = holder.lockCanvas()

            onDrawFrame(canvas)

            holder.unlockCanvasAndPost(canvas)
        }
    }

    private fun onDrawFrame(canvas: Canvas) {
        canvas.drawColor(Color.WHITE)
        //绘制背景
        for (h in 0 until heightCount) {
            for (w in 0 until widthCount) {
                vm.observeItem(w, h).value.apply {
                    getBitmap(this)?.let {
                        canvas.drawBitmap(it, w * itemSize, h * itemSize, null)
                    } ?: kotlin.run {
                        canvas.drawText(this.toString(), w * itemSize, h * itemSize, p)
                    }
                }
            }
        }
    }

    private fun getBitmap(state: Int): Bitmap? {
        return when (state) {
            ITEM_STATUS_UN_CLICK -> {
                itemStateBgInit
            }
            ITEM_STATUS_BLACK -> {
                itemStateBgClicked
            }
            ITEM_STATUS_BANG -> {
                itemStateBgBang
            }
            ITEM_STATUS_FLAG -> {
                itemStateBgFlag
            }

            else -> {
                //数字
                null
            }
        }

    }

    override fun surfaceDestroyed(holder: SurfaceHolder) {

    }
}